package com.wxprogram.smallprogram.controller;


import com.wxprogram.smallprogram.entity.UserStudent;
import com.wxprogram.smallprogram.entity.UserTeacher;
import com.wxprogram.smallprogram.service.FileService;
import com.wxprogram.smallprogram.service.UserInfoReqService;
import org.apache.commons.lang.SystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class FileHandleController {
    @Autowired
    private FileService fileService;

    @Autowired
    public UserInfoReqService userInfoReqService;

    @RequestMapping("/image")
    public String FileUpload(@RequestParam("degree")int degree,@RequestParam("code")int code,@RequestParam("file")MultipartFile file){
        //限制文件格式
        if (!file.isEmpty()){
            String filename = file.getOriginalFilename();
            String suffixList = "jpg,gif,png,ico,bmp,jpeg";
            String suffix = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
            if (!suffixList.contains(suffix.trim().toLowerCase())) {
                return "只能上传图片";
            }
            String path = "";
            if (SystemUtils.IS_OS_LINUX){
                path = "/home/images";
            }
            if (SystemUtils.IS_OS_WINDOWS){
                path = "F:\\weixin\\images";
            }
            System.out.print(path);
            File file1 = new File(path);
            if (!file1.exists()){
                file1.mkdirs();
            }
            String realname = UUID.randomUUID().toString() + filename;
            String filepath = path + File.separator + realname;
            File dest = new File(filepath);
            int count = fileService.insertImg(degree,code,filepath);
            if (count > 0){
                try {
                    file.transferTo(dest);
                    return "success";
                }catch (IOException e){
                    e.printStackTrace();
                    return "图片上传失败";
                }
            }else {
                return "error:failure";
            }

        }else {
            return  "上传失败，文件不能为空";
        }

    }
}
